package com.hibegin.http.server;

import com.hibegin.http.server.config.ServerConfig;
import com.hibegin.http.server.util.SslChannelFactory;
import com.szwistar.common.os.FileUtils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

import javax.net.ssl.SSLContext;

public class SimpleHttpsWebServer extends SimpleWebServer {
    private static final Logger LOG = LoggerFactory.getLogger(SimpleHttpsWebServer.class);

    // SSL 上下文
    @SuppressWarnings("unused")
	private SSLContext sslContext;

    public SimpleHttpsWebServer(ServerConfig serverConfig) throws Exception {
        super(serverConfig);

        // SSL Keystore
        InputStream keystore = null;
        String keystorePath = serverConfig.getSslKeystore();
        // SSL Keystore 的访问密码
        String password = serverConfig.getSslKeystorePassword();

        try {
            if (keystorePath.startsWith("classpath:")) {
            	keystorePath = keystorePath.substring("classpath:".length());
            	keystore = SimpleHttpsWebServer.class.getClassLoader().getResourceAsStream(keystorePath);
            } else {
                keystore = new FileInputStream(new File(keystorePath));
            }
            // 创建 SSL 上下文
            sslContext = SslChannelFactory.getSSLContext(keystore, password);
        } catch (Exception e) {
            LOG.error("", e);
        } finally {
        	FileUtils.close(keystore);
        }
    }

	@Override
	public int read(SocketChannel channel, ByteBuffer data) throws IOException {
		// TODO SSL 读
		return super.read(channel, data);
	}

	@Override
	public int write(SocketChannel channel, ByteBuffer data) throws IOException {
		// TODO SSL 写
		return super.write(channel, data);
	}
}
